package com.lcy.app.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Switch;
import android.widget.TextView;

import com.lcy.app.R;
import com.lcy.app.api.MusicApi;
import com.lcy.app.api.domain.BusinessFileDTO;
import com.lcy.app.api.domain.PlayMusic;
import com.lcy.app.api.domain.RespEntity;
import com.lcy.app.api.domain.SysBusinessFileDTO;
import com.lcy.app.api.http.HTTP;
import com.lcy.app.common.util.DownloadHelper;
import com.lcy.app.common.util.FileUtil;
import com.lcy.app.common.util.HttpUtil;
import com.lcy.app.common.util.ListUtil;
import com.lcy.app.common.util.StrUtil;
import com.lcy.app.common.util.ToastUtil;
import com.lcy.app.component.MusicPlay;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MusicItemActivity extends AppCompatActivity {
    private Map<Integer, PlayMusic> playMusicMap = new HashMap<>();
    private Map<Integer, MediaPlayer> mediaPlayerMap = new HashMap<>();
    private String dirName;
    private MusicPlay musicPlay;
    private PlayMusic currentPlayerMusic = new PlayMusic(false);
    private List<SysBusinessFileDTO> businessFileList = new ArrayList<>();
    private Integer currentPosition = null;
    private Switch currentMusicPlaySwitch;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_music_item);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        Intent intent = getIntent();
        String dirId = intent.getStringExtra("dirId");

        TextView dirnameView = findViewById(R.id.dirname);
        dirName = intent.getStringExtra("dirName");
        dirnameView.setText(dirName);

        currentMusicPlaySwitch = findViewById(R.id.musicPlay);
        musicPlay = new MusicPlay();

        HTTP<BusinessFileDTO> businessStraightFileDTOHTTP = new HTTP<>();
        RespEntity<BusinessFileDTO> musicResEntity = businessStraightFileDTOHTTP
                .synRequest(this, retrofit ->
                        retrofit.create(MusicApi.class).findSelfDomain(MainActivity.token, dirId));

        if (HttpUtil.isOk(musicResEntity)) {
            BusinessFileDTO straightFileDTO = musicResEntity.getData();
            if (ListUtil.isValid(straightFileDTO.getBusinessFileList())) {
                businessFileList = straightFileDTO.getBusinessFileList();
                dirName = String.format("%s[%s]", dirName, businessFileList.size());
                dirnameView.setText(dirName);
                listMusic();
            }
        }
    }

    public void listMusic() {
        List<String> fileList = new ArrayList<>(businessFileList.size());
        for (SysBusinessFileDTO e : businessFileList) {
            if (StrUtil.isValidWithoutBlank(e.getFileName())) {
                fileList.add(String.format("%s   %s", e.getOriginal(), e.getFormattedFileSize()));
            }
        }
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(
                MusicItemActivity.this, android.R.layout.simple_list_item_1, fileList);
        ListView listView = (ListView) findViewById(R.id.musicList);
        listView.setAdapter(adapter);

        // 初始化播放配置
        for (int i = 0; i < businessFileList.size(); i++) {
            playMusicMap.put(i, new PlayMusic(false));
        }

        listView.setOnItemClickListener((parent, view, position, id) -> {
            // 播放
            currentPosition = position;
            play(position);
        });
    }

    public void musicPlay(View view) {
        if (currentPosition != null) {
            play(currentPosition);
        }
    }

    public void musicOrderPlay(View view) {
        musicPlay.setMusicOrderPlay(!musicPlay.getMusicOrderPlay());
        musicPlay.setMusicCurrentOnePlay(false);
        musicPlay.setMusicCirclePlay(false);
        TextView dirnameView = findViewById(R.id.dirname);
        if (musicPlay.getMusicOrderPlay()) {
            dirnameView.setText(String.format("%s(顺序播放)", dirName));
        } else {
            dirnameView.setText(dirName);
        }
    }

    public void musicCurrentOnePlay(View view) {
        musicPlay.setMusicCurrentOnePlay(!musicPlay.getMusicCurrentOnePlay());
        musicPlay.setMusicCirclePlay(false);
        musicPlay.setMusicOrderPlay(false);
        TextView dirnameView = findViewById(R.id.dirname);
        if (musicPlay.getMusicCurrentOnePlay()) {
            dirnameView.setText(String.format("%s(单曲播放)", dirName));
        } else {
            dirnameView.setText(dirName);
        }
    }

    public void musicCirclePlay(View view) {
        musicPlay.setMusicCirclePlay(!musicPlay.getMusicCirclePlay());
        musicPlay.setMusicOrderPlay(false);
        musicPlay.setMusicCurrentOnePlay(false);
        TextView dirnameView = findViewById(R.id.dirname);
        if (musicPlay.getMusicCirclePlay()) {
            dirnameView.setText(String.format("%s(列表循环)", dirName));
        } else {
            dirnameView.setText(dirName);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 释放MediaPlayer资源
        for (Map.Entry<Integer, MediaPlayer> mediaPlayerEntry : mediaPlayerMap.entrySet()) {
            MediaPlayer mediaPlayer = mediaPlayerEntry.getValue();
            if (mediaPlayer != null) {
                mediaPlayer.release();
                mediaPlayer = null;
            }
        }
        playMusicMap.clear();
        mediaPlayerMap.clear();
        musicPlay = null;
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // 处理配置更改事件
    }

    /**
     * 播放
     */
    private void play(int position) {
        // 获取媒体
        MediaPlayer mediaPlayer = getMediaPlayer(position, DownloadHelper.getMusicLink(this,businessFileList.get(position).getFileId()));

        // 播放
        doOnPlay(position, mediaPlayer);
    }

    /**
     * 播放
     */
    private void doOnPlay(int position, MediaPlayer mediaPlayer) {
        PlayMusic playMusic = playMusicMap.get(position);
        if (!playMusic.getPlaying()) {
            // 暂停当前的播放
            if (currentPlayerMusic.getId() != null) {
                pauseMusic(mediaPlayerMap.get(currentPlayerMusic.getId()), playMusicMap.get(currentPlayerMusic.getId()));
            }
            // 开始播放
            mediaPlayer.start();
            playMusic.setPlaying(true);
            currentPlayerMusic.setId(position);
            currentMusicPlaySwitch.setChecked(true);
            TextView currentMusicName = findViewById(R.id.currentMusicName);
            currentMusicName.setText(businessFileList.get(position).getOriginal());
            ToastUtil.info(MusicItemActivity.this, "Play");
        } else {
            // 暂停播放
            pauseMusic(mediaPlayer, playMusic);
            currentPlayerMusic.setId(null);
            currentMusicPlaySwitch.setChecked(false);
        }
    }

    /**
     * 暂停
     */
    private void pauseMusic(MediaPlayer mediaPlayer, PlayMusic playMusic) {
        if (mediaPlayer.isPlaying()) {
            mediaPlayer.pause();
        }
        playMusic.setPlaying(false);
        ToastUtil.info(MusicItemActivity.this, "Pause");
    }

    /**
     * 从服务器获取媒体流
     */
    private MediaPlayer getMediaPlayer(int position, String url) {
        if (!mediaPlayerMap.containsKey(position)) {
            MediaPlayer mediaPlayer = getMediaPlayer(url, position);

            mediaPlayer.setOnCompletionListener(currentMediaPlayer -> {
                PlayMusic playMusic = playMusicMap.get(position);
                pauseMusic(currentMediaPlayer, playMusic);
                // 单曲播放
                if (musicPlay.getMusicCurrentOnePlay()) {
                    play(position);
                }
                // 顺序播放
                if (musicPlay.getMusicOrderPlay()) {
                    if (position < businessFileList.size() - 1) {
                        play(position + 1);
                    }
                }
                // 列表循环
                if (musicPlay.getMusicCirclePlay()) {
                    play(position < businessFileList.size() - 1 ? position + 1 : 0);
                }
                System.out.println("////////////监听结束");
            });

            mediaPlayerMap.put(position, mediaPlayer);
        }
        return mediaPlayerMap.get(position);
    }

    private MediaPlayer getMediaPlayer(String url, int position) {
        // 初始化MediaPlayer
        MediaPlayer mediaPlayer = new MediaPlayer();

        // 获取SD卡的根目录路径
        String innerStorageReadPath = getLocalFileUrl(position, true);
        boolean exists = new File(innerStorageReadPath).exists();
        if (!exists) {
            String innerStorageWritePath = getLocalFileUrl(position, false);
            // 如果不存在，则下载
            DownloadHelper.downloadFile(getApplicationContext(),
                    DownloadHelper.getMusicLink(this,businessFileList.get(position).getFileId()),
                     innerStorageWritePath);
        }

        // 设置MediaPlayer的数据源
        try {
            if (exists) {
                // 本地有取本地
                mediaPlayer.setDataSource(innerStorageReadPath);
            } else {
                // 本地无文件
                mediaPlayer.setDataSource(getApplicationContext(), Uri.parse(url));
            }

            mediaPlayer.prepare(); // 准备播放
            return mediaPlayer;
        } catch (IOException e) {
            ToastUtil.error(MusicItemActivity.this, "获取媒体失败");
            throw new RuntimeException("获取媒体失败");
        }
    }

    private String getLocalFileUrl(int position, boolean read) {
        // 获取SD卡的根目录路径
//        String sdCardPath = Environment.getExternalStorageDirectory().getAbsolutePath();
        // 设置MP3文件的路径，这里假设MP3文件在SD卡根目录下的 "your_directory" 文件夹中，文件名为 "your_audio.mp3"
//        return sdCardPath + "/main-project/music/" + businessFileList.get(position).getFileId() + ".mp3";
        String originalType = businessFileList.get(position).getType();
        String type = StrUtil.isValidWithoutBlank(originalType) ? "." + originalType : "";
        String fileUrl = "music/" + businessFileList.get(position).getFileId() + type;
        return FileUtil.getProjectExternalRootPath(read) + fileUrl;
    }
}
